package cn.xo68.ide.plugin.action;

import cn.xo68.ide.plugin.common.PluginPathUtils;
import cn.xo68.ide.plugin.common.component.StarupApplicationComponent;
import cn.xo68.ide.plugin.common.ui.form.GenerateCodeDialog;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Files;
import java.nio.file.Paths;

public class GenerateCodeAction extends AnAction {

    private static Logger logger = LoggerFactory.getLogger(GenerateCodeAction.class);

    @Override
    public void actionPerformed(AnActionEvent e) {
        StarupApplicationComponent.getInstance().setLastOperateProject(e.getProject());

        Project selectedProject = e.getProject();
        // 当前选中的目录
        VirtualFile selectedFile = e.getData(LangDataKeys.VIRTUAL_FILE);

        if(!selectedFile.isDirectory()){
            logger.warn("请选择项目、模板进行操作");
            return;
        }

        String target=PluginPathUtils.getCodeGenereateConfigPath(selectedFile);
        if(!Files.exists(Paths.get(target))){
            logger.warn("代码生成配置不存在，请先创建");
            return;
        }

        GenerateCodeDialog.open(selectedProject,selectedFile);
    }

    @Override
    public void update(AnActionEvent e) {
        VirtualFile selectedFile = e.getData(LangDataKeys.VIRTUAL_FILE);

        String target= PluginPathUtils.getCodeGenereateConfigPath(selectedFile);

        boolean flag=false;
        if(Files.exists(Paths.get(target))){
            flag =true;
        }
        e.getPresentation().setEnabledAndVisible(flag);
    }
}
